package org.way.iam.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.way.iam.component.SaTokenComponent;
import org.way.iam.entity.SysUserEntity;
import org.way.iam.service.ISysUserService;

import javax.annotation.Resource;

@RestController
@Api(tags = "登录相关")
public class LoginController {

    @Resource
    private ISysUserService userService;

    @Resource
    private SaTokenComponent saTokenComponent;

    @ApiOperation("登录")
    @PostMapping("/login")
    @ApiImplicitParams({
            @ApiImplicitParam(name="username",value = "用户名",required = true),
            @ApiImplicitParam(name="password",value = "密码",required = true)})
    public SaResult login(String username,String password) {
        SysUserEntity user = userService.getUser(username);
        if(user == null) {
            return SaResult.error("账号或密码错误");
        }
        if(!user.getPassword().equals(password)) {
            return SaResult.error("账号或密码错误");
        }
        StpUtil.login(user.getId());
        saTokenComponent.setSession(user);
        return SaResult.data(StpUtil.getTokenInfo());
    }

    @ApiOperation("登出")
    @GetMapping("/logout")
    public SaResult logout() {
        StpUtil.logout();
        return SaResult.ok();
    }

    @ApiOperation("登出")
    @GetMapping("/logout/{userId}")
    public SaResult logout(@PathVariable String userId) {
        StpUtil.logout(userId);
        return SaResult.ok();
    }

    @ApiOperation("是否登录")
    @GetMapping("/isLogin")
    public SaResult isLogin() {
        return SaResult.data(StpUtil.isLogin());
    }

    @ApiOperation("获取当前登陆人的token")
    @GetMapping("/token")
    public SaResult getToken() {
        return SaResult.data(StpUtil.getTokenInfo());
    }
}
